<template>
  <el-drawer class="drawer_warp" title="选择用户" :visible.sync="drawerPvVisible" size="800px"
    :close-on-press-escape="false" :before-close="handleClose">
    <div class="filter-container g-bgc-fill-el-input">
      <div class="filter-left">详情
        <np-input-search v-model="listQuery.keyword" placeholder="搜索登录账号、手机号" @all-search="comHandleFilterAllSearch" />
      </div>
    </div>

    <el-table class="g-el-table" :data="list" v-loading="listLoading" ref="tableRef"
      @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55">
      </el-table-column>
      <el-table-column label="头像">
        <div slot-scope="{row}" class="profile_picture_warp">
          <img :src="profilePictureSrc(row)" v-if="profilePictureSrc(row)">
          <div v-else></div>
        </div>
      </el-table-column>
      <el-table-column label="昵称" align="center" width="300">
        <template slot-scope="{row}">
          <span>{{ row.nickName }}</span>
        </template>
      </el-table-column>
      <el-table-column label="手机号">
        <template slot-scope="{row}">
          <span>{{ row.username }}</span>
        </template>
      </el-table-column>
    </el-table>

    <np-pagination v-show="total > 0" :total="total" :page.sync="listQuery.pageNum" :limit.sync="listQuery.pageSize"
      :page-sizes="pageSizes" @pagination="getList" />

    <div class="fotter">
      <el-button type="warning" plain @click="handleClearAllClick">取消所有选择</el-button>
      <div>
        <el-button type="warning" @click="handleBeSureClick" :loading="submitLoading">确定</el-button>
        <el-button type="info" plain class="btn1" @click="handleCancelClick">取消</el-button>
      </div>
    </div>
  </el-drawer>
</template>
<script>
import { getAllUsers } from '@/api/family-and-users-management/user'

export default {
  props: {
    visible: {
      type: Boolean,
      default: false
    },
    brandOptions: {
      type: Array,
      default: () => {
        return []
      }
    },
    infoData: {
      type: Array,
      default: () => {
        return []
      }
    },
  },
  filters: {
    statusFilter(status) {
      const statusMap = {
        published: 'success',
        draft: 'info',
        deleted: 'danger'
      }
      return statusMap[status]
    },
  },
  data() {
    return {
      list: null,
      total: 0,
      pageSizes: [10, 20, 30, 40, 50, 60, 70, 80, 90, 100],
      // 页面初始化调接口加载 Loading
      listLoading: true,

      // isFirstLoad: true, // 初始化标志位

      multipleOldCurSelection: [],// 当前列表所有条件选中的数据，不管添加还是删除，都做一个缓存
      multipleNewCurSelection: [],// 当前列表所有条件选中的数据，不管添加还是删除，都做一个缓存
      /**
       * @multipleSelection
       * 选中数组,每次选择往后添加，如果删除就删除选中的一些选项
       * 存取的是 infoData里面的初始数据，及每次点击 取消所有选择 按钮之后的数据 的和
       */
      multipleSelection: [],// 选中数组,每次选择往后添加，如果删除就删除选中的一些选项
      // multipleCacheSelection: [],// 选中数组的缓存，存取的是 infoData里面的初始数据，及每次点击 取消所有选择 按钮之后的数据 的和
      // isClearAll: false, // 判断是否点击过 取消所有选择 按钮之后的数据

      // 页面筛选初始参数对象
      listQuery: {
        pageNum: 1,
        pageSize: 10,

        keyword: undefined,
      },

      // 以上都是列表参数，以下都是弹窗本身参数
      drawerPvVisible: false,

      submitLoading: false,
    }
  },
  watch: {
    visible: {
      handler(newVal) {
        this.drawerPvVisible = newVal;
        if (newVal) {
          if (!this.infoData) {
            this.editInfo()
            return
          }
        }
        if (!newVal) {
          this.resetFieldsFrom()
        }
      }
    }
  },
  computed: {
  },
  created() {
    this.getList()
  },
  methods: {
    profilePictureSrc(row) {
      try {
        let base_url = process.env.VUE_APP_IMG_BASE_URL,
          url = row.headUrl;
        if (url) {
          return `${base_url}/${url}`
        }
      } catch (error) { }
      return ""
    },
    editInfo() {
      this.multipleSelection = JSON.parse(JSON.stringify(this.infoData))
      // this.getList()
    },
    resetFieldsFrom() {
      // this.isClearAll = false
      this.drawerPvVisible = false
      this.$emit("update:visible", this.drawerPvVisible)
    },
    handleClose(done) {
      this.resetFieldsFrom()
      done()
    },
    handleCancelClick() {
      this.list.filter(el => {
        if (this.multipleSelection.find(v_el => el.id === v_el.id)) {
          this.$refs.tableRef.toggleRowSelection(el, true);
        } else {
          this.$refs.tableRef.toggleRowSelection(el, false);
        }
      })
      this.resetFieldsFrom()
    },
    handleClearAllClick() {
      this.multipleSelection = []
      this.$refs.tableRef.clearSelection();
    },
    handleBeSureClick() {
      let receiverName = []
      try {
        let old_arr = this.multipleOldCurSelection.map((el) => el),
          new_arr = this.multipleNewCurSelection.map((el) => el);

        let del_arr = old_arr.filter(o_el => {
          let v = new_arr.find(n_el => {
            return o_el.id === n_el.id
          })
          return !v
        })

        // 删除
        if (del_arr.length) {
          // console.log('删除', same_arr);
          del_arr.forEach(o_el => {
            let index = -1;
            this.multipleSelection.forEach((v_el, idx) => {
              if (o_el.id === v_el.id) {
                index = idx;
              }
            });
            if (index > -1) {
              this.multipleSelection.splice(index, 1);
            }
          })
        }

        // 添加
        new_arr.filter(n_el => {
          let index = -1;
          this.multipleSelection.forEach((v_el, idx) => {
            if (n_el.id === v_el.id) {
              index = idx;
            }
          });
          // 添加新的
          if (index === -1) {
            this.multipleSelection.push({ ...n_el });
          }
        })
        receiverName = this.multipleSelection;
      } catch (error) {
        console.log(error);
      }
      this.$emit("addSelectSuccessChange", receiverName)
      this.resetFieldsFrom()
    },
    handleSelectionChange(val) {
      this.multipleOldCurSelection = JSON.parse(JSON.stringify(this.multipleNewCurSelection))
      this.multipleNewCurSelection = val
    },
    getList() {
      this.listLoading = true
      getAllUsers(this.listQuery).then(res => {
        if (res.code === 200) {
          this.list = res.data.list
          this.total = res.data.total

          this.$nextTick(() => {
            this.list.filter(el => {
              if (this.multipleSelection.find(v_el => el.id === v_el.id)) {
                this.$refs.tableRef.toggleRowSelection(el, true);
              }
            })

            // Just to simulate the time of the request
            this.listLoading = false
          });
        } else {
          this.listLoading = false
        }
      }).catch(() => {
        this.listLoading = false
      })
    },
    comHandleFilterAllSearch(e, type) {
      this.listQuery.pageNum = 1
      this.getList()
    },
    comHandleFilterSelectChange(e) {
      this.listQuery.pageNum = 1
      this.getList()
    },
    comHandleFilterDateChange(e) {
      this.listQuery.pageNum = 1
      this.listQuery.startDate = e ? e[0] : ''
      this.listQuery.endDate = e ? e[1] : ''
      this.getList()
    },
  }
}
</script>
<style lang="scss" scoped>
.title {
  padding-bottom: 32px;
  font-size: 18px;
  font-weight: 500;
  line-height: 24px;
  color: #15181D;
}

.fotter {
  padding-top: 88px;
  display: flex;
  justify-content: space-between;
  align-items: center;

  .btn1 {
    margin-right: 12px;
  }
}

.profile_picture_warp {
  display: flex;
  justify-content: center;
  align-items: center;

  @mixin com_img {
    width: 40px;
    height: 40px;
    border-radius: 50%;
    flex-shrink: 0;
  }

  img {
    @include com_img;
  }

  div {
    @include com_img;
    background: #CCCCCC;
  }
}

.container {
  ::v-deep {
    @media (max-width: 1280px) {
      .np-el-d-body {
        padding: 24px 40px 40px 24px;
        min-height: 264px;
      }
    }
  }
}

.drawer_warp {
  &::v-deep {
    &.el-drawer__wrapper {
      pointer-events: none;

      .el-drawer {
        pointer-events: auto;
      }

      .el-drawer__body {
        padding: 0 40px 40px;
        overflow: auto;
      }
    }
  }
}

::v-deep {
  .np-pagination-total {
    max-width: 106px;
  }
}
</style>